#!/bin/bash

load inquirer

help() {
  echo "Usage:"
  echo "  zpackage release <package>"
  echo ""
}

core() {
  if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    help
    exit 0
  fi
  
  local name=$1
  if [ -z "$name" ]; then
    log::error "package name is requried"
    exit 1
  fi

  local name=$1
  if [ -z "$name" ]; then
    log::error "[$(timestamp)][zpackage::release] name is required"
    exit 1
  fi

  local package_path=$(zpackage::get_package_path $name)
  if [ ! -d "$package_path" ]; then
    log::error "[$(timestamp)][zpackage::release] package(${name}) not found"
    exit 1
  fi

  cd $package_path
  local origin_version=$(zpackage::version $name)
  required() {
    if [ "$1" = "" ]; then
      echo false
    else
      echo true
    fi
  }

  inquirer::text "input new version(origin: ${origin_version}):" new_version "" "version is required" required

  sed -i -e "s/${origin_version}/$new_version/" mod >>/dev/null 2>&1

  #@TODO mod-e file occurred
  if [ -f "mod-e" ]; then
    rm mod-e >>/dev/null 2>&1
  fi

  # not git
  if [ ! -d ".git" ]; then
    git init
    git remote add origin https://github.com/zmicro-design/package-${name}.git
    git add .
  fi

  git add mod
  git commit -m "chore(release): bumped version to ${new_version}"
  git tag ${new_version}
  git push origin ${new_version}
  git push origin master

  log::success "[zpackage][release] ${plugin_name} ${new_version}"
}

run() {
  core $@
}

run $@
